package cn.q3c.parse.impl.oscache;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.text.SimpleDateFormat;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import cn.keyvalue.ccf.common.object.DetailPage;
import cn.keyvalue.ccf.common.object.Image;
import cn.q3c.parse.base.BaseParse;

/**
 * OScache页面解析
 * @author wangxinning
 *
 */
public class OSchinaParseImpl implements BaseParse {

	private static final Logger logger = Logger
			.getLogger(OSchinaParseImpl.class);

	public Object parse(String url, File file, String abouturl, File aboutFile) {

		try {
			Document doc = Jsoup.parse(FileUtils.readFileToString(file));
			doc.setBaseUri(url);

			// 标准元素获取
			String title = doc.title();
			String description = doc.select("meta[name=description]").attr(
					"content");
			String keywords = doc.select("meta[name=keywords]").attr("content");
			DetailPage page = new DetailPage();
			page.setUrl(url);
			page.setTitle(StringUtils.trimToEmpty(title));
			page.setDescription(StringUtils.trimToEmpty(description));
			page.setKeywords(StringUtils.trimToEmpty(keywords));

			// 内容标题
			String contenttitle = doc.select("div[class=NewsEntity] > h1").text();
			
			page.setBodytitle(StringUtils.trimToEmpty(contenttitle));

			// 发表时间
			String dateTime = doc.select("div[class=PubDate]").text();
			dateTime = StringUtils.trimToEmpty(StringUtils.substringBetween(dateTime, "发布于：", "("));
			if (StringUtils.isNotBlank(dateTime)) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
				page.setDatetime(sdf.parse(dateTime));
			}

			// 内容，遇到p填入换行标记
			Elements bodyElements = doc.select("div[class=Body NewsContent TextContent]").select("p");			
			String bodyStr = "";
			// 内容中的图片
			List<Image> images = new ArrayList<Image>();
			for (int i = 0; i < bodyElements.size(); i++) {
				String tempLine = bodyElements.get(i).text();
				bodyStr += "<!--b-->" + tempLine + "<!--/b-->";

				// 判断图片
				Elements imgElements = bodyElements.get(i).select("img");
				if (imgElements != null && !imgElements.isEmpty()) {
					for (int z = 0; z < imgElements.size(); z++) {
						Image img = new Image();
						img.setSrc(imgElements.get(z).attr("abs:src"));
						img.setAlt(imgElements.get(z).attr("alt"));// alt
						img.setWidth(NumberUtils.toInt(imgElements.get(z).attr(
								"width")));
						img.setHeight(NumberUtils.toInt(imgElements.get(z)
								.attr("height")));
						images.add(img);
					}
				}
			}
			page.setBody(bodyStr);
			if (!images.isEmpty()) {
				page.setImages(images);
			}

			//返回内容打印
			logger.debug("page:" + page);

			return page;

		} catch (Exception e) {

			logger.error("解析OScache详情页异常", e);
		}

		return null;
	}
	
	
	
	
	public static void main( String[] args ) throws Exception
	{
		OSchinaParseImpl oscacheParse = new OSchinaParseImpl();
		
		String url = "http://www.oschina.net/news/42480/fwknop-2-5-released";
		
		Document doc = Jsoup.connect(url).timeout((int)DateUtils.MILLIS_PER_MINUTE).userAgent("").get();		
		String content = doc.html();
		
		File f = new File( SystemUtils.getJavaIoTmpDir().toString() + File.separator + "aaa" );
		FileUtils.writeStringToFile(f, content);
		
		//oscacheParse.parse(url, f);
		
	}
}